package com.harmontronics.hanma.paas.paas.domain.tenant.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.harmontronics.hanma.paas.paas.consts.DbConstants;
import com.harmontronics.hanma.paas.paas.consts.NumberEnum;
import com.harmontronics.hanma.paas.paas.consts.ValidateConstants;
import com.harmontronics.hanma.paas.paas.domain.tenant.consts.HmTenantUserFields;
import com.harmontronics.hanma.paas.paas.domain.tenant.entity.valueobject.I18nKeyEnum;
import com.harmontronics.hanma.paas.paas.domain.tenant.repository.persistence.HmTenantUserRepository;
import com.harmontronics.hanma.paas.paas.domain.tenant.entity.HmTenantUser;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import com.harmontronics.hanma.paas.paas.token.TenantUserTokenKit;
import com.harmontronics.hanma.paas.paas.utils.PasswordUtil;
import com.harmontronics.hanma.paas.paas.utils.RequestUtils;
import com.harmontronics.hanma.paas.paas.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.harmontronics.hanma.paas.paas.common.PageBase;

import com.harmontronics.hanma.paas.paas.domain.tenant.repository.mapper.HmTenantUserMapper;
import com.harmontronics.hanma.paas.paas.domain.tenant.repository.po.HmTenantUserPO;
import java.util.List;
import java.util.Optional;

@Service("hmTenantUserService")
public class HmTenantUserService{

    @Autowired
    private HmTenantUserRepository hmTenantUserRepository;

    @Autowired
    private TenantUserTokenKit tenantUserTokenKit;

    @Cacheable(value = "tenantUser",key = "#p0")
    public HmTenantUser findById( Long id){
            HmTenantUserPO po =   hmTenantUserRepository.getById(id);
        return BeanUtil.toBean(po,HmTenantUser.class);
    }

    public void save(HmTenantUser hmTenantUser){
        HmTenantUserPO po =  BeanUtil.toBean(hmTenantUser,HmTenantUserPO.class);
        Long tenantId = tenantUserTokenKit.getUserInfo().getTenantId();
        //租户下用户名唯一校验
        validateField(ValidateConstants.TENANT_USER_NAME,po.getUserName());
        Map<String,String> pwdMap = PasswordUtil.generatePassword(po.getPwd());
        po.setPwd(pwdMap.get(HmTenantUserFields.PWD));
        po.setSalt(pwdMap.get(HmTenantUserFields.SALT));
        po.setTenantId(tenantId);
        hmTenantUserRepository.save(po);
        hmTenantUser.setId(po.getId());
    }

    /**
     * 租户用户属性唯一性校验
     * @param key
     * @param value
     */
    public void validateField(String key,String value){
        Long tenantId = tenantUserTokenKit.getUserInfo().getTenantId();
        QueryWrapper<HmTenantUserPO> wrapper = new QueryWrapper<>();
        if(ValidateConstants.TENANT_USER_NAME.equalsIgnoreCase(key)){
            key = HmTenantUserFields.USER_NAME;
            wrapper.eq(key,value);
            wrapper.eq(HmTenantUserFields.TENANT_ID,tenantId);
            wrapper.eq(HmTenantUserFields.DELETED,NumberEnum.ZERO.getNum());
            validateFieldImpl(key,wrapper);
        }
    }

    private void validateFieldImpl(String key,QueryWrapper wrapper) {
        HmTenantUserPO user = hmTenantUserRepository.getOne(wrapper);
        if (Optional.ofNullable(user).isPresent()) {
            if (HmTenantUserFields.USER_NAME.equalsIgnoreCase(key)) {
                throw new ErrorKeyException(I18nKeyEnum.USERNAME_INDATA);
            }
        }
    }

    @CacheEvict(value = "tenantUser",key = "#p0")
    public HmTenantUser updateStatus(Long userId,Integer status){
            HmTenantUserPO po =  hmTenantUserRepository.getById(userId);
            po.setStatus(status);
            hmTenantUserRepository.updateById(po);
            return BeanUtil.toBean(po,HmTenantUser.class);
    }

    public void remove(List<Long> ids){
            hmTenantUserRepository.removeByIds(ids);
    }


    public PageBase<HmTenantUser> getList(int pageNo,int pageSize,String tenantUserName){
        QueryWrapper<HmTenantUserPO> wrapper = new QueryWrapper<>();
        wrapper.eq(HmTenantUserFields.TENANT_ID, tenantUserTokenKit.getUserInfo().getTenantId());
        wrapper.eq(HmTenantUserFields.DELETED, NumberEnum.ZERO.getNum());
        if(StringUtil.isNotBlank(tenantUserName)){
            wrapper.like(HmTenantUserFields.USER_NAME,tenantUserName);
        }
        wrapper.orderByDesc(HmTenantUserFields.ID);
        Page<HmTenantUserPO> page = new Page<>(pageNo, pageSize);
        IPage<HmTenantUserPO> resultPage =
                    hmTenantUserRepository.selectPage(wrapper,page);
        return PageBase.from(resultPage,HmTenantUser.class);
    }

    public HmTenantUser getUserByName(Long tenantId,String userName){
        //获取数据库中的用户信息
        QueryWrapper<HmTenantUserPO> wrapper = new QueryWrapper<>();
        wrapper.eq(HmTenantUserFields.TENANT_ID,tenantId);
        wrapper.eq(HmTenantUserFields.USER_NAME,userName);
        wrapper.eq(HmTenantUserFields.DELETED, NumberEnum.ZERO.getNum());
        return Convert.convert(HmTenantUser.class,hmTenantUserRepository.getOne(wrapper)) ;
    }
    @CacheEvict(value = "tenantUser",key = "#p0.id")
    public void resetPassword(HmTenantUser hmTenantUser){
        HmTenantUserPO po =  BeanUtil.toBean(hmTenantUser,HmTenantUserPO.class);
        Map<String,String> pwdMap = PasswordUtil.generatePassword(po.getPwd());

        po.setPwd(pwdMap.get(DbConstants.PWD));
        po.setSalt(pwdMap.get(DbConstants.SALT));
        hmTenantUserRepository.updateById(po);
    }

}